package br.com.mobimenu.facade.impl;

import java.util.Collection;

import br.com.mobimenu.business.Service;
import br.com.mobimenu.facade.Facade;
import br.com.mobimenu.model.Entidade;
import br.com.mobimenu.model.impl.Usuario;
import br.com.mobimenu.persistence.filter.impl.FiltroGeneric;

public abstract class FacadeGeneric implements Facade {

	private Service<?, ?, ?, ?> services[];

	public FacadeGeneric(Service<?, ?, ?, ?>... services) {
		this.services = services;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Entidade buscar(Class classe, Long id) {
		return this.getService(classe).buscar(id);
	}

	@SuppressWarnings("unchecked")
	public Collection<Entidade> consultar(FiltroGeneric<?> filtro) {
		return this.getService(filtro.getClassEntidade()).consultar(filtro);
	}

	@SuppressWarnings("unchecked")
	public void editar(Entidade vo, Usuario usuario) {
		this.getService(vo.getClass()).editar(vo, usuario);
	}

	@SuppressWarnings("unchecked")
	public void excluir(Entidade vo, Usuario usuario) {
		this.getService(vo.getClass()).excluir(vo);
	}

	@SuppressWarnings("rawtypes")
	public Service getService(Class entity) {
		Service serviceTarget = null;
		for (Service service : this.services) {
			Class classe = service.getClassEntidade();
			if(classe.equals(entity)) {
				serviceTarget = service;
			}
		}
		return serviceTarget;
	}

	@SuppressWarnings("unchecked")
	public void inserir(Entidade vo, Usuario usuario) {
		this.getService(vo.getClass()).inserir(vo, usuario);
	}

}
